<?php
namespace application\admin\controllers;

use Yii;
use mz\ars\Links;
use mz\controllers\AdminController as Controller;

class LinksController extends Controller
{
    #友情链接列表
    public function actionIndex()
    {
        $links = Links::find()->asArray()->all();
        return $this->render('index',compact('links'));
    }

    public function actionAdd()
    {
        $id = Yii::$app->request->get('id','');
        $links = empty($id) ? [] : Links::find()->where(['id' => $id])->asArray()->one();

         # 链接图片转换
        if (!empty($links['picture']))$links['picture'] = 'http://img.mzcms.com/'.$links['picture'];

        return $this->render('index',compact('links'));

    }

    # 执行保存的操作
    public function actionSave()
    {
        $post = Yii::$app->request->post();

        if (empty($post))return $this->ajaxReturn(['e' => 1,'m' => '提交数据不能为空']);
        $pageObj = !empty($post['id']) ? Links::find()->where(['id' => $post['id']])->one() : new Links();
        array_filter($post,function($key){
            return in_array($key,['title','desc','picture','url']);
        },ARRAY_FILTER_USE_KEY);

        $pageObj->attributes = $post;
        if ($pageObj->validate()){
            if ($pageObj->save())return $this->ajaxReturn(['e' => 0 , 'm' => '数据保存成功！']);
        } else {
            return $this->ajaxReturn(['e' => 0 , 'm' => '数据验证失败！']);
        }

        return $this->ajaxReturn(['e' => 1, 'm' => '很遗憾，数据保存失败~']);
    }
}